# -*- coding:utf-8 -*-
# ==========================================
#       Author: ZiChen
#        Mail: 1538185121@qq.com
#         Time: 2021/06/20
#           Version: 1.0
#             QQ音乐官方API
# ==========================================
from urllib import request, parse
import re
import base64
import json


class Song():
    '''
    单曲信息获取
    '''

    def __init__(self, songmid):
        self.songmid = songmid
        self.api_lyrics_Url = 'http://c.y.qq.com/lyric/fcgi-bin/fcg_query_lyric_new.fcg'  # 官方API
        self.api_details_url = "https://y.qq.com/n/ryqq/songDetail/%s" % songmid

    def Lyrics_GET(self):

        # 发送的数据
        data = {
            "songmid": self.songmid,
            "g_tk": "5381",
            "loginUin": "0",
            "hostUin": '0',
            "inCharset": 'utf8',
            "outCharset": 'utf-8',
            "notice": "0",
            "platform": 'yqq',
            "needNewCode": "0",
        }

        # 表头，要加Referer
        headers = {
            "Referer": 'https://y.qq.com',
        }
        # 2021/06/20 将data转换为bytes，不然会报错
        params = parse.urlencode(data).encode(encoding='UTF8')
        req_detail = request.Request(
            url=self.api_lyrics_Url, data=params, headers=headers)
        res_detail = request.urlopen(req_detail)
        # 获取响应的json字符串
        str_json_detail = res_detail.read().decode('utf-8')
        # 直接提取歌词（base64，需要解码）
        lyrics_bytes = re.findall(
            r"(?<=\"lyric\"\:\")(.*)(?=\",)", str_json_detail)[0]

        # 解码后返回
        return {"lyric": str(base64.b64decode(lyrics_bytes), 'utf-8')}

    def Details_GET(self):

        headers = {
            "user-agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36 Edg/91.0.864.41'
        }
        req_detail = request.Request(
            url=self.api_details_url, headers=headers)
        res_detail = request.urlopen(req_detail)
        # 获取响应的json字符串
        str_json_detail = res_detail.read().decode('utf-8')
        # 歌曲名
        name = re.findall(
            r"(?<=\<h1\sclass\=\"data__name_txt\")(.*)(?=\<\/h1\>)", str_json_detail)[0].split('>')[-1]
        # 原始数据，需要进一步处理
        singer_ori = re.findall(
            r"(?<=\"data__singer_txt\")(.*)(?=\<\/a\>\<\/div\>\<ul\sclass\=\"data__info\"\>)", str_json_detail)[0]
        # 多个歌手用列表
        singerLst = []
        for i in re.findall(r"(?<=title)=([^?&=h]*)", singer_ori):
            singerLst.append(i.replace('"', '').replace(' ', ''))

        if len(singerLst) > 1:  # 有两个作者及以上的时候再拼接
            singer = "/".join(singerLst)
        else:
            singer = singerLst[0]

        return {"name": name,
                "ar": singer}


class SongList():
    # 2021/06/27 🧰新增歌单歌曲信息获取
    def __init__(self, songListID):
        self.id = songListID
        self.api_details_url = 'http://c.y.qq.com/qzone/fcg-bin/fcg_ucc_getcdinfo_byids_cp.fcg'

    def Details_GET(self):
        '''
        获取歌单详情，包括歌曲名、作者/翻唱者、歌曲mid
        '''
        # 发送的数据
        data = {
            "type": "1",
            "utf8": "1",
            "disstid": self.id,  # 歌单的id
            "loginUin": "0",
        }

        # 表头，要加Referer
        headers = {
            "Referer": 'https://y.qq.com/n/yqq/playlist',
        }
        # 2021/06/20 将data转换为bytes，不然会报错
        params = parse.urlencode(data).encode(encoding='UTF8')
        req_detail = request.Request(
            url=self.api_details_url, data=params, headers=headers)
        res_detail = request.urlopen(req_detail)
        # 获取响应的json字符串
        str_json_detail = res_detail.read().decode('utf-8').replace(')',
                                                                    '').replace('(', '').replace('jsonCallback', '')
        # 把json转换成字典
        myjson_playList = json.loads(str_json_detail)

        # 获取所需信息
        Result = {}  # 处理完毕后返回的字典
        # 2021/06/27 ⚙ 歌单详情
        dissDetail = myjson_playList['cdlist'][0]
        dissid = dissDetail['dissid']  # 歌单ID
        dissname = dissDetail['dissname']  # 歌单名
        nickname = dissDetail['nickname']  # 歌单作者名
        songnum = dissDetail['songnum']  # 歌单所含歌曲数

        Result['diss'] = {'dissid': dissid,
                          'dissname': dissname,
                          'nickname': nickname,
                          'songnum': songnum}
        # 2021/06/27 ⚙ 歌单歌曲详情
        # 2021/06/27 ‼ 获得的是列表，每个元素是一首歌曲
        songListData = []  # 用于装处理后的歌曲信息的列表
        songListDetail = myjson_playList['cdlist'][0]['songlist']
        for i in songListDetail:
            singerLst = []
            if len(i['singer']) > 1:  # 2021/06/27 ‼ 歌手信息也是一个列表
                for s in i['singer']:
                    singerLst.append(s['name'])
                singer = "/".join(singerLst)
            else:
                singer = i['singer'][0]['name']
            songmid = i["songmid"]
            songname = i["songname"]

            songListData.append({'singer': singer,
                                 'songmid': songmid,
                                 'songname': songname})

        Result['songListDetail'] = songListData

        return Result
        # 2021/06/27 ‼ 返回的Result结构示意：
        # {'diss':
        #   {
        #   'dissid': dissid,
        #       'dissname': dissname,
        #       'nickname': nickname,
        #       'songnum': songnum
        #   },
        #   'songListDetail':
        #   [
        #       {
        #       'singer': singer,
        #       'songmid': songmid,
        #       'songname': songname
        #       }
        #   ]
        # }
